import axios from 'axios';
import { Dialog } from 'antd-mobile';
const instance = axios.create({
    baseURL: '/api',
    timeout: 100 * 1000,
});

instance.interceptors.request.use(
    (config: any) => config,
    (error: any) => Promise.reject(error)
);

instance.interceptors.response.use(
    (response: any) => response,
    (error: { response: { status: any; }; }) => {
        if (error && error.response) {
            switch (error.response.status) {
                case 401:
                    Dialog.alert({
                        content: 'HTTP 401，请重新登录后重试！',
                        closeOnMaskClick: true,
                    })
                    break;
                default:
                    Dialog.show({
                        title: 'Error',
                        content: `请求异常：${error.response.status}`
                    });
                    break;
            }
        }
        return Promise.reject(error);
    }
);

function myhttp(method: string, url: string, options: any) {
    return instance.request<any>({
        method,
        url,
        ...options,
    })
        .then((el: any) => {
            // if (el.data.code === 500) {
            //     Dialog.show({
            //         title: 'Error',
            //         content: el.data.msg,
            //     });
            //     return Promise.reject(el);
            // }
            return Promise.resolve(el);
        })
        .catch((err: any) => {
            console.error(err);
        });
}

const http = {
    get(url: string, options: any = {}) {
        return myhttp('get', url, options);
    },
    post(url: string, options: any = {}) {
        return myhttp('post', url, options);
    },
    delete(url: string, options: any = {}) {
        return myhttp('delete', url, options);
    },
    put(url: string, options: any = {}) {
        return myhttp('put', url, options);
    },
};

export default http;